<template>
  <div class="validate-input pb-3">
    <input
      type="text"
      class="form-control"
      :class="{'is-invalid': inputRef.error}"
      v-model="inputRef.val"
      @blur="validateInput"
    />
    <span v-show="inputRef.error" class="invalid-feedback">{{inputRef.message}}</span>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, PropType } from 'vue'

const emailReg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
interface RuleProp {
  type: 'required' | 'email';
  message: string;
}

export type RulesProp = RuleProp[]
export default defineComponent({
  name: 'ValidateInput',
  props: {
    rules: {
      type: Array as PropType<RulesProp>,
      required: true
    }
  },
  setup (props) {
    // 当前input项
    const inputRef = reactive({
      val: '',
      error: false,
      message: ''
    })
    // 检查input项
    const validateInput = () => {
      const allPassed = props.rules.every((item) => {
        let passed = true
        inputRef.message = item.message
        switch (item.type) {
          case 'required':
            passed = inputRef.val.trim() !== ''
            break
          case 'email':
            passed = emailReg.test(inputRef.val)
            break
          default:
            break
        }
        return passed
      })
      inputRef.error = !allPassed
    }
    return {
      inputRef,
      validateInput
    }
  }
})
</script>

<style lang="scss">
</style>
